
import 'package:flutter_cipher/flutter_cipher.dart';
import 'package:flutter/services.dart' show rootBundle;

import 'dart:convert';
import 'dart:typed_data';
class MyDeEncrypt{

  static Future<String> decodeString(String content) async{
    var publicKeyStr = await rootBundle.loadString('assets/data/rsa_public_key.pem');
    var publicKey =  RSAKeyParser().parse(publicKeyStr);
    Asymmetric rsa = Cipher.getAsymmetricInstance(RSA(publicKey: publicKey));

    Uint8List sourceBytes = base64.decode(content);
    int inputLen = sourceBytes.length;
    int maxLen = 128;
    String totalBytes = "";
    print("inputLen = $inputLen");
    for (var i = 0; i < inputLen; i += maxLen) {
      int endLen = inputLen - i;
      Uint8List item;
      if (endLen > maxLen) {
        item = sourceBytes.sublist(i, i + maxLen);
      } else {
        item = sourceBytes.sublist(i, i + endLen);
      }
      Encrypted en = Encrypted(item);
      String s =  rsa.decryptPublic(en);
      totalBytes = totalBytes + s;
    }
    return  totalBytes;
  }
  static Future<String> encodeString(String content) async{
    var publicKeyStr = await rootBundle.loadString('assets/data/rsa_public_key.pem');
    var publicKey = RSAKeyParser().parse(publicKeyStr);
    Asymmetric rsa = Cipher.getAsymmetricInstance(RSA(publicKey: publicKey));

    List<int> sourceBytes = utf8.encode(content);
    int inputLen = sourceBytes.length;
    int maxLen = 117;
    List<int> totalBytes = List();
    for (var i = 0; i < inputLen; i += maxLen) {
      int endLen = inputLen - i;
      List<int> item;
      if (endLen > maxLen) {
        item = sourceBytes.sublist(i, i + maxLen);
      }
      else {
        item = sourceBytes.sublist(i, i + endLen);
      }
      print("item = $item");
      List<int> byte = rsa.encryptPublic(item.toString()).bytes;
      totalBytes.addAll(byte);
    }
    return base64.encode(totalBytes);
  }
//  static Future<String> encodeString(String content) async{
//    var publicKeyStr = await rootBundle.loadString('assets/data/rsa_public_key.pem');
//    var publicKey = RSAKeyParser().parse(publicKeyStr);
//    Asymmetric rsa = Cipher.getAsymmetricInstance(RSA(publicKey: publicKey));
//
//    int inputLen = content.length;
//    int maxLen = 117;
//    List<int> totalBytes = List();
//    for (var i = 0; i < inputLen; i += maxLen) {
//      int endLen = inputLen - i;
//      String item;
//      if (endLen > maxLen) {
//        item = content.substring(i, i + maxLen);
//      }
//      else {
//        item = content.substring(i, i + endLen);
//      }
//      print("item = $item");
//      List<int> byte = rsa.encryptPublic(item).bytes;
//      totalBytes.addAll(byte);
//    }
//    return base64.encode(totalBytes);
//  }
}